package com.bai.ucenter.controller;

import com.bai.ucenter.entity.ConstantWxUtils;
import com.bai.ucenter.entity.Member;
import com.bai.ucenter.service.MemberService;
import com.bai.utils.HttpClientUtils;
import com.bai.utils.JwtUtils;
import com.google.gson.Gson;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;

@Controller
@RequestMapping("/api/ucenter/wx")
@CrossOrigin
public class WxApiController {

    @Autowired
    private MemberService memberService;

    //生成微信扫描二维码
    @GetMapping("login")
    public String getWxCode() {
        String url = "https://open.weixin.qq.com/connect/qrconnect" +
                "?appid=%s" +
                "&redirect_uri=%s" +
                "&response_type=code" +
                "&scope=snsapi_login" +
                "&state=%s" +
                "#wechat_redirect ";
        //对url进行编码
        String redirect_url = ConstantWxUtils.WX_OPEN_REDIRECT_URL;
        try {
            URLEncoder.encode(redirect_url, "utf-8");
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }
        String.format(
                url,
                ConstantWxUtils.WX_OPEN_APP_ID,
                redirect_url,
                "bai"
        );
        //请求微信地址
        return "redirect:" + url;
    }

    //获取扫描人信息，添加数据
    @GetMapping("callback")
    public String callback(String code, String state) {
        try {
            System.out.println("code" + code + ",state" + state);
            //获取code值
            //拿着code获取access_token和openid
            String baseAccessTokenUrl = "https://api.weixin.qq.com/sns/oauth2/access_token" +
                    "?appid=%s" +
                    "&secret=%s" +
                    "&code=%s" +
                    "&grant_type=authorization_code";
            String accessTokenUrl = String.format(
                    baseAccessTokenUrl,
                    ConstantWxUtils.WX_OPEN_APP_ID,
                    ConstantWxUtils.WX_OPEN_APP_APPSECRET,
                    code,
                    "bai"
            );
            //请求拼接地址返回access_token和openid
            String accessTokenInfo = HttpClientUtils.get(accessTokenUrl);
            System.out.println("accessTokenInfo" + accessTokenInfo);

            Gson gson = new Gson();
            HashMap mapAccessToken = gson.fromJson(accessTokenInfo, HashMap.class);
            String accessToken = (String) mapAccessToken.get("access_token");
            String openid = (String) mapAccessToken.get("openid");

            Member member = memberService.getOpenIdMenber(openid);
            if (member == null) {
                String baseUserInfoUrl = "https://api.weixin.qq.com/sns/userinfo" +
                        "?access_token=%s" +
                        "&openid=%s";
                String userInfoUrl = String.format(
                        baseUserInfoUrl,
                        accessToken,
                        openid
                );
                //用户数据
                String userInfo = HttpClientUtils.get(userInfoUrl);
                System.out.println(userInfo);
                HashMap userInfoMap = gson.fromJson(userInfo, HashMap.class);
                String nickName = (String) userInfoMap.get("nickname");
                String headimgurl = (String) userInfoMap.get("headimgurl");
                //扫码人信息添加到数据库里
                member = new Member();
                member.setOpenid(openid);
                member.setNickname(nickName);
                member.setAvatar(headimgurl);
                memberService.save(member);
            }
           //使用jwt生成token
            String jwtToken = JwtUtils.getJwtToken(member.getId(), member.getNickname());
            return "redirect:http://localhost:3000?token="+jwtToken;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
